package com.gouying.web.scheduled;


import com.gouying.web.service.SeckillService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 秒杀商品的定时上架
 *      每天晚上3点，上架最近三天需要秒杀的商品
 *      当天0:00:00 - 23::59:59
 *      明天0:00:00 - 23::59:59
 *      后天0:00:00 - 23::59:59
 * @author ly
 */
@Slf4j
@Service
@AllArgsConstructor(onConstructor_ = @Autowired)
public class SecKillSkuScheduled {

    SeckillService seckillService;

    RedissonClient redissonClient;

    private final String uploadLock = "seckill:upload:lock";

    @Scheduled(cron = "* * * * * ?")
    public void uploadSecKillSkuLatest3Days(){
        //1、重复上架无需处理
        log.info("上架秒杀的商品信息……");
        //分布式锁解决秒杀商品重复上架问题.
        //锁的业务执行完成，状态已经更新完成。释放锁以后，其他人获取到就会拿到最新的状态
        RLock lock = redissonClient.getLock(uploadLock);
        //锁10秒
        lock.lock(10, TimeUnit.SECONDS);
        try {
            //拿到分布式锁，上架秒杀商品和活动信息到redis
            seckillService.uploadSecKillSkuLatest3Days();
        }finally {
            //解锁
            lock.unlock();
        }
    }
}
